package com.yunhe.merchants.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.exception.ObjectNotFoundException;
import com.yunhe.common.exception.code.ErrorCode;
import feign.FeignException;
import feign.Response;
import feign.codec.ErrorDecoder;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * @ClassName DefaultErrorDecoder
 * @Description TODO
 * @Author HeTao
 * @Date 2021/6/25 11:22
 * @Version 1.0
 **/
public class DefaultErrorDecoder extends ErrorDecoder.Default {
    @SneakyThrows
    @Override
    public Exception decode(String s, Response response) {
        FeignException exception = (FeignException)super.decode(s, response);

        if (response.status() == HttpStatus.BAD_REQUEST.value()){
            if(response.headers().get(String.valueOf(ErrorCode.CODE.OBJECT_NOTFOUND.value())).iterator().hasNext()){
                throw new ObjectNotFoundException(URLDecoder.decode(response.headers().get(String.valueOf(ErrorCode.CODE.OBJECT_NOTFOUND.value())).iterator().next(),"UTF-8"));
            }
        }


        String body = exception.contentUTF8();
        if(StringUtils.isNotEmpty(body)){
            JSONObject res = JSON.parseObject(body);
            if(res.containsKey("message")){
                if(res.containsKey("message")){
                    throw new ArgumentErrorException(res.getString("message"));
                }
                //throw new ArgumentErrorException(res.getString("message"));
            }
        }
        return exception;
    }

}
